package com.awesome.network.response;

import android.os.Handler;
import android.os.Looper;

import com.awesome.network.callback.OnProgressListener;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

/**
 * Author: JFangZ
 * Email:janezhang1901@163.com
 * Date: 2020/7/2 15:44
 * Description:下载文件时的代理 ResponseBody,在这里面可以回调下载进度
 */
public class DownloadResponseBody extends ResponseBody {
    private final ResponseBody mResponseBody;
    private final OnProgressListener mListener;
    private long mCurrentLen;
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public DownloadResponseBody(ResponseBody responseBody, OnProgressListener onProgressListener, long currentLen) {
        mResponseBody = responseBody;
        mListener = onProgressListener;
        mCurrentLen = currentLen;
    }

    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(mResponseBody.source()) {
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long read = super.read(sink, byteCount);
                if (read == -1) {
                    return read;
                }
                mCurrentLen += read;
                if (mListener != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mListener.onProgress(mCurrentLen, mResponseBody.contentLength());
                        }
                    });
                }
                return read;
            }
        });
    }
}